﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApp1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        static async Task Test()
        {
            using (HttpClient client = new HttpClient())
            {
                string url = "http://example.com"; // 替换为你想访问的URL
                try
                {
                    HttpResponseMessage response = await client.GetAsync(url);
                    response.EnsureSuccessStatusCode();
                    string responseBody = await response.Content.ReadAsStringAsync();
                    Console.WriteLine(responseBody);
                }
                catch (HttpRequestException e)
                {
                    Console.WriteLine("\nException Caught!");
                    Console.WriteLine("Message :{0} ", e.Message);
                }
            }
        }
        System.Timers.Timer timer = new System.Timers.Timer();
        private void btn_Start_Click(object sender, EventArgs e)
        {
            timer.Enabled = true;
            timer.Elapsed += Timer_Elapsed;
        }
        private void Timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            if (!this.IsDisposed)
            {
                this.Invoke(new Action(() =>
                  {
                      if (this != null)
                          this.textBox1.Text += DateTime.Now.ToLongTimeString() + "\r\n";
                  }));
            }
        }

        private void btn_Stop_Click(object sender, EventArgs e)
        {
            timer.Enabled = false;
        }

        private void btn_FileRename_Click(object sender, EventArgs e)
        {
            ThreadPool.QueueUserWorkItem((obj) =>
            {
                string picPath = @"H:\超速取证\备份\格式1";
                DirectoryInfo dir = new DirectoryInfo(picPath);
                if (dir == null)
                    return;
                try
                {
                    FileSystemInfo[] files = dir.GetFileSystemInfos();
                    for (int i = 0; i < files.Length; i++)
                    {
                        FileInfo nextFile = files[i] as FileInfo;
                        string originalName = nextFile.Name;
                        int index = originalName.IndexOf('_');
                        string newName = DateTime.Now.ToString("yyyyMMddHHmmss") + "_" + originalName.Substring(index + 1);
                        string newPath = picPath + "\\" + newName;
                        // 确保目标文件名不存在，否则 Move 方法会抛出 IOException
                        if (File.Exists(newPath))
                        {
                            File.Delete(newPath);
                        }
                        // 重命名文件
                        File.Move(nextFile.FullName, newPath);

                        Thread.Sleep(500);
                    }
                    this.Invoke(new Action(() =>
                    {
                        this.textBox1.Text += DateTime.Now.ToLongTimeString() + " 重命名文件名成功\r\n";
                    }));
                }
                catch (Exception ex)
                {
                    this.Invoke(new Action(() =>
                    {
                        this.textBox1.Text += DateTime.Now.ToLongTimeString() + " 重命名文件名失败:" + ex.Message + "\r\n";

                    }));
                }
            });
        }

        private void btn_Copy_Click(object sender, EventArgs e)
        {
            string sourceFolder = @"H:\超速取证\备份\格式1";
            string destinationFolder = @"H:\超速取证\test";
            try
            {
                // 确保目标文件夹存在
                Directory.CreateDirectory(destinationFolder);
                // 获取源文件夹中的所有文件
                string[] files = Directory.GetFiles(sourceFolder);

                // 遍历所有文件，并将它们复制到目标文件夹
                foreach (string file in files)
                {
                    // 获取文件名
                    string fileName = Path.GetFileName(file);
                    // 构建目标文件路径
                    string destFile = Path.Combine(destinationFolder, fileName);
                    // 复制文件
                    File.Copy(file, destFile, true); // true 表示如果目标文件存在，则覆盖它
                }

                this.textBox1.Text += DateTime.Now.ToLongTimeString() + " 文件复制成功\r\n";
            }
            catch (Exception ex)
            {
                this.textBox1.Text += DateTime.Now.ToLongTimeString() + " 文件复制失败:" + ex.Message + "\r\n";
            }
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (MessageBox.Show("你真的要关闭?", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning) == DialogResult.OK)
                e.Cancel = false;
            else
                e.Cancel = true;
        }

        private void btn_Exit_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void btnAlxaPic_Click(object sender, EventArgs e)
        {
            Task.Run(new Action(() =>
            {
                string picPath = @"H:\测试照片\超速\备份";
                DirectoryInfo dir = new DirectoryInfo(picPath);
                if (dir == null)
                    return;
                try
                {
                    FileSystemInfo[] files = dir.GetFileSystemInfos();
                    for (int i = 0; i < files.Length; i++)
                    {
                        FileInfo nextFile = files[i] as FileInfo;
                        string originalName = nextFile.Name;
                        int index = originalName.IndexOf('_');
                        string newName = DateTime.Now.ToString("yyyyMMddHHmmssfff") + "_" + originalName.Substring(index + 1);
                        string newPath = picPath + "\\" + newName;
                        // 重命名文件
                        File.Move(nextFile.FullName, newPath);

                        Thread.Sleep(500);
                    }
                    this.Invoke(new Action(() =>
                    {
                        this.textBox1.Text += DateTime.Now.ToLongTimeString() + " 生成文件成功\r\n";
                    }));

                    CopyAlxaPic();
                }
                catch (Exception ex)
                {
                    this.Invoke(new Action(() =>
                    {
                        this.textBox1.Text += DateTime.Now.ToLongTimeString() + " 生成文件失败:" + ex.ToString() + "\r\n";
                    }));
                }
            }));
        }

        private void CopyAlxaPic()
        {
            string sourceFolder = @"H:\测试照片\超速\备份";
            string destinationFolder = @"H:\测试照片\超速\阿拉善";
            try
            {
                // 确保目标文件夹存在
                Directory.CreateDirectory(destinationFolder);
                // 获取源文件夹中的所有文件
                string[] files = Directory.GetFiles(sourceFolder);

                // 遍历所有文件，并将它们复制到目标文件夹
                foreach (string file in files)
                {
                    // 获取文件名
                    string fileName = Path.GetFileName(file);
                    // 构建目标文件路径
                    string destFile = Path.Combine(destinationFolder, fileName);
                    // 复制文件
                    File.Copy(file, destFile, true); // true 表示如果目标文件存在，则覆盖它
                }
                this.Invoke(new Action(() =>
                {
                    this.textBox1.Text += DateTime.Now.ToLongTimeString() + " 文件复制成功\r\n";
                }));
            }
            catch (Exception ex)
            {
                this.Invoke(new Action(() =>
                {
                    this.textBox1.Text += DateTime.Now.ToLongTimeString() + " 文件复制失败:" + ex.Message + "\r\n";
                }));
            }
        }
        System.Timers.Timer timerWenzhou =new System.Timers.Timer();
        private void btnWenzhou_Click(object sender, EventArgs e)
        {
            timerWenzhou.Enabled = true;
            timerWenzhou.Interval = 10 * 60 * 1000;
            timerWenzhou.Elapsed += timerWenzhou_Elapsed;

            //timerWenzhou_Elapsed(null,null);
        }

        int flag = 0;//全局变量
        private void timerWenzhou_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            if (Interlocked.Exchange(ref flag, 1) == 0)
            {
                string path = @"D:\desktop\Mine\喀什\备份\新建文件夹 ";
                string picPath = "";
                string s = "330382080713210000";
                long ii = 10;
                for (int j = 1; j < 28; j++)
                {
                    ii = ii + 1;
                    string bh = s + ii;
                    picPath = path + $"({j})";
                    DirectoryInfo dir1 = new DirectoryInfo(picPath);

                    if (dir1 == null)
                        return;
                    foreach (var item in dir1.GetDirectories())
                    {
                        try
                        {
                            FileSystemInfo[] files = item.GetFileSystemInfos();
                            for (int i = 0; i < files.Length; i++)
                            {
                                FileInfo nextFile = files[i] as FileInfo;
                                string originalName = nextFile.Name;
                                string[] a1 = originalName.Split('_');
                                string newName = DateTime.Now.ToString("yyyyMMddHHmmssfff")
                                + "_" + a1[1]
                                + "_" + a1[2]
                                + "_" + bh
                                + "_" + a1[4]
                                + "_" + a1[5]
                                + "_" + a1[6]
                                + "_" + a1[7]
                                + "_" + a1[8]
                                + "_" + a1[9]
                                + "_" + a1[10];
                                string newPath = picPath + "\\" + item.Name+ "\\" + newName;
                                // 重命名文件
                                File.Move(nextFile.FullName, newPath);

                                Thread.Sleep(50);
                            }
                            this.Invoke(new Action(() =>
                            {
                                this.textBox1.Text += DateTime.Now.ToLongTimeString() + " 生成文件成功\r\n";
                            }));
                        }
                        catch (Exception ex)
                        {
                            this.Invoke(new Action(() =>
                            {
                                this.textBox1.Text += DateTime.Now.ToLongTimeString() + " 生成文件失败:" + ex.ToString() + "\r\n";
                            }));
                        }
                    }
                }
                string sourceFolder = @"D:\desktop\Mine\喀什\备份";
                string destinationFolder = @"D:\desktop\Mine\喀什\违章";
                CopyFolder(sourceFolder, destinationFolder);

                Interlocked.Exchange(ref flag, 0);
            }
        }

        /// <summary>
        /// 复制文件夹及文件,包括根目录
        /// </summary>
        /// <param name="sourceFolder">原文件路径</param>
        /// <param name="destFolder">目标文件路径</param>
        /// <returns></returns>
        public int CopyFolder2(string sourceFolder, string destFolder)
        {
            try
            {
                string folderName = System.IO.Path.GetFileName(sourceFolder);
                string destfolderdir = System.IO.Path.Combine(destFolder, folderName);
                string[] filenames = System.IO.Directory.GetFileSystemEntries(sourceFolder);
                foreach (string file in filenames)// 遍历所有的文件和目录
                {
                    if (System.IO.Directory.Exists(file))
                    {
                        string currentdir = System.IO.Path.Combine(destfolderdir, System.IO.Path.GetFileName(file));
                        if (!System.IO.Directory.Exists(currentdir))
                        {
                            System.IO.Directory.CreateDirectory(currentdir);
                        }
                        CopyFolder2(file, destfolderdir);
                    }
                    else
                    {
                        string srcfileName = System.IO.Path.Combine(destfolderdir, System.IO.Path.GetFileName(file));
                        if (!System.IO.Directory.Exists(destfolderdir))
                        {
                            System.IO.Directory.CreateDirectory(destfolderdir);
                        }
                        System.IO.File.Copy(file, srcfileName);
                    }
                }
                return 1;
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message);
                return 0;
            }
        }

        /// <summary>
        /// 复制文件夹及文件,不包括根目录
        /// </summary>
        /// <param name="sourceFolder">原文件路径</param>
        /// <param name="destFolder">目标文件路径</param>
        /// <returns></returns>
        public int CopyFolder(string sourceFolder, string destFolder)
        {
            try
            {
                //如果目标路径不存在,则创建目标路径
                if (!System.IO.Directory.Exists(destFolder))
                {
                    System.IO.Directory.CreateDirectory(destFolder);
                }
                //得到原文件根目录下的所有文件
                string[] files = System.IO.Directory.GetFiles(sourceFolder);
                foreach (string file in files)
                {
                    string name = System.IO.Path.GetFileName(file);
                    string dest = System.IO.Path.Combine(destFolder, name);
                    System.IO.File.Copy(file, dest);//复制文件
                }
                //得到原文件根目录下的所有文件夹
                string[] folders = System.IO.Directory.GetDirectories(sourceFolder);
                foreach (string folder in folders)
                {
                    string name = System.IO.Path.GetFileName(folder);
                    string dest = System.IO.Path.Combine(destFolder, name);
                    CopyFolder(folder, dest);//构建目标路径,递归复制文件
                }
                return 1;
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message);
                return 0;
            }
        }
    }
}
